// 先把Image等高等宽放大最大限度的填满高或者宽
// 剩余部分用边缘延长

class ImageCover extends eui.Component {
	texture: egret.Texture;

	sheet: egret.SpriteSheet;

	override childrenCreated(): void {
		super.childrenCreated();
		this.addEventListener(egret.Event.RESIZE, this.onResize, this);
	}

	onResize(): void {
		this.update();
	}

	async setImage(file: string): Promise<void> {
		const texture = await loadTextureByUrl(file);
		if (this.sheet) {
			this.sheet.dispose();
		}
		if (this.texture) {
			this.texture.dispose();
		}
		this.texture = texture;
		this.sheet = new egret.SpriteSheet(texture);
		this.update();
	}

	update(): void {
		if (!this.texture) {
			return;
		}
		this.removeChildren();

		const tex = this.texture;
		const center = new egret.Bitmap(tex);
		center.width = tex.textureWidth;
		center.height = tex.textureHeight;
		this.addChild(center);

		if (tex.textureWidth >= this.width && tex.textureHeight >= this.height) {
			center.x = (this.width - center.width) / 2;
			center.y = (this.height - center.height) / 2;
			return;
		}

		if (tex.textureWidth < this.width && tex.textureHeight < this.height) {
			const sx = this.width / tex.textureWidth;
			const sy = this.height / tex.textureHeight;
			const scale = Math.min(sx, sy);
			center.width = scale * tex.textureWidth;
			center.height = scale * tex.textureHeight;
			if (sx === sy) { return; }
		}

		center.x = (this.width - center.width) / 2;
		center.y = (this.height - center.height) / 2;
		if (center.width >= this.width) {
			const toptex = this.sheet.createTexture('top', 0, 0, tex.textureWidth, 1);
			const top = new egret.Bitmap(toptex);
			top.x = center.x;
			top.y = 0;
			top.width = center.width;
			top.height = center.y;
			this.addChild(top);

			const bottomtex = this.sheet.createTexture('bottom', 0, tex.textureHeight - 1, tex.textureWidth, 1);
			const bottom = new egret.Bitmap(bottomtex);
			bottom.x = top.x;
			bottom.y = center.y + center.height;
			bottom.width = top.width;
			bottom.height = top.height;
			this.addChild(bottom);
		} else if (center.height >= this.height) {
			const ltex = this.sheet.createTexture('left', 0, 0, 1, tex.textureHeight);
			const left = new egret.Bitmap(ltex);
			left.x = 0;
			left.y = center.y;
			left.width = center.x;
			left.height = center.height;
			this.addChild(left);

			const rtex = this.sheet.createTexture('right', tex.textureWidth - 1, 0, 1, tex.textureHeight);
			const right = new egret.Bitmap(rtex);
			right.x = center.x + center.width;
			right.y = left.y;
			right.width = left.width;
			right.height = left.height;
			this.addChild(right);
		}
	}
}
